package ajax.conrtroller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AjaxController extends HttpServlet {
	private static final long serialVersionUID = 1L;
  
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String cmd = request.getParameter("cmd");
		if(cmd.equals("calc")) {
			calculate(request,response);
		}else if(cmd.equals("getHello")){
			getHello(request, response);
		}else if(cmd.equals("idcheck")){
			idCheck(request, response);
		}
	}
	
	protected void idCheck(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ArrayList<String> list = new ArrayList<String>();
		//등록됭 ID들 즉, 사용불가
		list.add("111111");
		list.add("222222");
		list.add("333333");
		list.add("444444");
		
		String id = request.getParameter("id");
		
		//중복 ID인지 체크
		boolean flag = list.contains(id);//true : 중복ID(사용 X) , false : 사용 O
		
		//응답 처리 
		response.setContentType("type/html;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(flag);

	}
	
	protected void calculate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException	{
		//1. 요청 파라미터 조회
		int num1 = Integer.parseInt(request.getParameter("num1"));
		int num2 = Integer.parseInt(request.getParameter("num2"));
		//2. 비지니스 로직 처리
		int result = num1+num2;
		//3. 응답
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-control", "no-cache");
		PrintWriter out = response.getWriter();
		out.println("계산결과 : " +result);
		
		
	}
	
	protected void getHello(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1. 요청 파라미터 조회
		String name = request.getParameter("name");
		
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-control", "no-cache");
		PrintWriter out = response.getWriter();
		out.println(name);
		System.out.println(name);
	}

	
}
